import { createClient } from 'redis';

import {
    RedisConfigType,
    ClientCreate,
    RedisClientTypes,
    ClientCreateCallback,
    RedisConnect,
} from '../../types/redis';

const clientCreate: ClientCreate = async (
    config: RedisConfigType,
    callback: ClientCreateCallback,
) => {
    const client: RedisClientTypes = createClient(config);
    client.on('error', err => {
        callback(client, err);
    });
    await client.connect();
    callback(client, null);
};

const redisConnect: RedisConnect = (options: RedisConfigType) =>
    new Promise((resolve, reject) => {
        clientCreate(options, (conn: RedisClientTypes, err) => {
            if (err) {
                reject(err);
            }
            resolve(conn); // 返回连接的 redis 对象
        });
    });

export default redisConnect;
